#include "uAnalyserAudioInput.h"


/*******************************************
 * uAnalyserAudioInput
 *******************************************/

uAnalyserAudioInput::uAnalyserAudioInput()
{
    outputBuffer = new QBuffer(this);

    QAudioDeviceInfo info = QAudioDeviceInfo::defaultInputDevice();
    QAudioFormat format = info.preferredFormat();
    format.setFrequency(22050);
    format.setChannels(1);
    format.setSampleSize(16);
    //format.setCodec("audio/pcm");
    format.setByteOrder(QAudioFormat::LittleEndian);
//    format.setSampleType(QAudioFormat::UnSignedInt);
    format.setSampleType(QAudioFormat::UnSignedInt);

    audio = new QAudioInput(format,this);
    outputByteArray = NULL;
    connect(outputBuffer, SIGNAL(bytesWritten(qint64)), this, SLOT(bufferUpdated(qint64)));
}

uAnalyserAudioInput::~uAnalyserAudioInput()
{
    stopRecording();
    delete audio;
}

void uAnalyserAudioInput::startRecording(int sample_rate, int buffer_size, QVector<double> *v)
{
    voltage = v;
    bufferLength = buffer_size;
    writtenAudioBytes = 0;
    outputByteArray = new QByteArray(bufferLength*10,0);
    outputBuffer->setBuffer(outputByteArray);
    outputBuffer->open( QIODevice::ReadWrite );
    writtenAudioBytes  = 0;
    voltage->clear();
    voltage->fill(0, bufferLength);
    audio->start(outputBuffer);
}

void uAnalyserAudioInput::pauseRecording(bool t)
{
    //true - pause recording
    if (audio->state() == QAudio::ActiveState && t)
        audio->suspend();
    else if (audio->state() == QAudio::SuspendedState && !t)
        audio->resume();
}

void uAnalyserAudioInput::stopRecording()
{
    audio->stop();
    outputBuffer->close();
    if (outputByteArray)
    {
        delete outputByteArray;
        outputByteArray = NULL;
    }
}

void uAnalyserAudioInput::bufferUpdated(qint64 bytesWritten)
{
    writtenAudioBytes += bytesWritten;
    if (writtenAudioBytes >= bufferLength*2)
    {
        for (int i=0, j=0; i<bufferLength; i++, j+=2)
            (*voltage)[i] = (double)(outputByteArray->at(j+1)*256 + outputByteArray->at(j))/32767.0;
        outputBuffer->seek(0);
        writtenAudioBytes = 0;
        emit audioBufferRefreshed();
    }
}
